<?php

namespace App\Http\Controllers\Admin\Config\Sms;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\Admin\Config\ConfigController;

use App\Models\Config;
use Validator;
use Illuminate\Validation\Rule;

class SetController extends AdminController
{
    /**
     * 获取单条key值
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function getKey($key){
        $where = ['key'=>$key];
        $this->ajaxJson(0,'',Config::where($where)->orderBy('created_at','desc')->get()->toArray());
    }

    /**
     * 更新KEY值
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function updateKey(Request $request){
    	$data  = $request->all();
		$validator = $this->formValidator($data);
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        $configController  = new ConfigController();
        foreach ($data as $key => $vue) {
        	$tranData = [];
        	$tranData['key'] = $key;
        	$tranData['vue'] = $vue;
        	$configController->updateByKey($tranData);	
        }
        $this->ajaxJson(0,'更新成功');
    }

    /**
     * 数据验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
			'sms'                              => '短信服务商',
			'sms_account_juhe'                 => '聚合短信服务商账户配置值',
			'sms_account_dayu_accesskeyid'     => '大于accessKeyId',
			'sms_account_dayu_accesskeysecret' => '大于accessKeySecret',
			'sms_account_dayu_signname'        => '大于短信签名',
        );

        $message  = array(
            'required'    => ':attribute必须填写',
        );

        $v =  Validator::make($data, [
			'sms' => ['required',Rule::in(['dayu','juhe'])],
        ],$message,$attribute);
        $v->sometimes('sms_account_juhe','required',function($data){
        	if($data['sms']=='juhe'){
        		return true;
        	}
        	return false;
        });
        $v->sometimes('sms_account_dayu_accesskeyid','required',function($data){
        	if($data['sms']=='dayu'){
        		return true;
        	}
        	return false;
        });
        $v->sometimes('sms_account_dayu_accesskeysecret','required',function($data){
        	if($data['sms']=='dayu'){
        		return true;
        	}
        	return false;
        });
        $v->sometimes('sms_account_dayu_signname','required',function($data){
        	if($data['sms']=='dayu'){
        		return true;
        	}
        	return false;
        });
        return $v;
    }
}
